package net.caixiaomi.info.service;

import android.app.Service;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import net.caixiaomi.info.BuildConfig;
import net.caixiaomi.info.model.UpdateEntity;
import net.caixiaomi.info.net.RetrofitManage;
import net.caixiaomi.info.util.Constants;
import net.caixiaomi.info.util.Dirs;
import net.caixiaomi.info.util.FileHelper;
import net.caixiaomi.info.util.LLog;
import net.caixiaomi.info.util.MD5Utils;
import net.caixiaomi.info.util.MyUtil;
import net.caixiaomi.info.util.NotificationHelper;
import net.caixiaomi.info.util.ProgressListener;
import net.caixiaomi.info.util.ToastUtil;

import org.reactivestreams.Subscriber;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class DownLoadService extends Service {
    public static final String current_count = "currentCount";
    public static final String count = "count";
    public static final String isFish = "done";
    public static final String action = "com.cmxa.action.Update";
    private static final String apkDir = "apk";
    public static final String url = "apk_url";
    public static final String UPDATE_KEY = "update_key";
    private ProgressListener progressListener;
    private Intent sendIntent;
    private NotificationHelper notificationHelper;
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        sendIntent = new Intent(action);
        getNotifyHelper();
    }

    private NotificationHelper getNotifyHelper(){
        if(notificationHelper == null){
            notificationHelper = new NotificationHelper(this);
        }
        return notificationHelper;
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null) {

            UpdateEntity update = (UpdateEntity) intent.getSerializableExtra(UPDATE_KEY);
            downloadApk(update);
        }
        return super.onStartCommand(intent, flags, startId);
    }

    public void downloadApk(final UpdateEntity update) {
        if(TextUtils.isEmpty(update.getUrl())){
            ToastUtil.s("下载地址错误");
            return;
        }

        final File file= new File(
                FileHelper.getSdcardRoot()
                , "cxma.apk");

//        String fileMD5 = "";
//        try {
//            if(file.exists()){
//                fileMD5 = MD5Utils.getFileMD5String(file.getPath());
//                if(fileMD5.equals(update.urlMd5)){
//                    install(file, update.urlMd5);
//                    return;
//                }
//            }
//        } catch (IOException e) {
//            LLog.e(e.getMessage());
//        }
        getNotifyHelper().setPendingIntent(getInstallIntent(file));
        if (progressListener == null) {
            progressListener = new ProgressListener() {
                @Override
                public void update(long bytesRead, long contentLength, boolean done) {
                    sendIntent.putExtra(count, contentLength);
                    sendIntent.putExtra(current_count, bytesRead);
                    sendIntent.putExtra(isFish, done);
                    if(contentLength == 0){
                        ToastUtil.s("文件破损");
                        return;
                    }
                    int i = (int) (bytesRead * 100 / contentLength);
                    getNotifyHelper().notifyDownLoad(i,done);
                    LocalBroadcastManager.getInstance(DownLoadService.this).sendBroadcast(sendIntent);
                }
            };
        }
//        Toast.makeText(getApplicationContext(),"开始下载",Toast.LENGTH_LONG).show();
//        ToastUtil.show(R.string.start_download);
        RetrofitManage.DownLoadService(update.getUrl(), progressListener, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) {
                InputStream is = response.body().byteStream();
                FileOutputStream fos = null;
                try {
                    fos = new FileOutputStream(file);
                    int len = 0;
                    byte[] buffer = new byte[8192];
                    while (-1 != (len = is.read(buffer))) {
                        //LLog.i("len = " + len);
                        fos.write(buffer, 0, len);
                    }
                    fos.flush();
                    fos.close();
                    is.close();
                    install(file);
                } catch (Exception e) {
                    LLog.e(e.getMessage());
                } finally {
                    try {
                        if (is != null) {
                            is.close();
                        }
                        if (fos != null) {
                            fos.close();
                        }
                    } catch (Exception e) {
                        LLog.e(e.getMessage());
                    }
                }
            }
        });
    }

    /**
     * install app
     *
     * @param apkFile
     */
    private void install(File apkFile) {
        LLog.e("apkFile = " + apkFile.getPath());
        if (!apkFile.exists()) {
            ToastUtil.s("文件破损");
            return;
        }



        if (apkFile.length() > 0 && apkFile.exists() && apkFile.isFile()) {
            startActivity(getInstallIntent(apkFile));
        }

//        String fileMD5 = "";
//        try {
//            fileMD5 = MD5Utils.getFileMD5String(apkFile.getPath());
//        } catch (IOException e) {
//            LLog.e(e.getMessage());
//        }
//        if (fileMD5.equals(serverMD5)) {
//            if (apkFile.length() > 0 && apkFile.exists() && apkFile.isFile()) {
//                startActivity(getInstallIntent(apkFile));
//            }
//        }else {
//            MyUtil.deleteDir(apkFile);
////            Observable<String> observable=Observable.create(new ObservableOnSubscribe<String>() {
////                @Override
////                public void subscribe(ObservableEmitter<String> e) throws Exception {
////                    Toast.makeText(getApplicationContext(),"文件破损",Toast.LENGTH_LONG).show();
////                }
////            }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
////            observable.subscribe();
////            AppExecutors.excuteMain(() -> ToastUtil.show(R.string.file_error));
//        }
    }
    private Intent getInstallIntent(File file){
        Intent i = new Intent(Intent.ACTION_VIEW);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {

                i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                Uri contentUri = FileProvider.getUriForFile(this, getPackageName() + ".fileprovider", file);
                i.setDataAndType(contentUri, "application/vnd.android.package-archive");
            } else {
                i.setDataAndType(Uri.parse("file://" + file), "application/vnd.android.package-archive");
                i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            }
           return i;
    }
}